package com.cndongtai.service.light;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cndongtai.dao.impl.DtuDao;
import com.cndongtai.dao.impl.LightDao;
import com.cndongtai.map.GDMapServer;
import com.cndongtai.po.Dtu;
import com.cndongtai.po.Light;
import com.cndongtai.util.DateUtil;
import com.cndongtai.vo.LightBean;

@Service("lightService")
public class LightService {

	@Resource(name="lightDao")
	private LightDao lightDao;
	
	@Resource(name="dtuDao")
	private DtuDao dtuDao;
	
	private GDMapServer mapServer = new GDMapServer();
	
	public Object[] addLight(String dtuIdStr, String lightNum,Double longitudeArr, Double latitudeArr) {
		Object[] result = new Object[2];
		
		Integer dtuId = Integer.valueOf(dtuIdStr);
		Dtu dtu = dtuDao.queryDtuById(dtuId);
		if(dtu==null) {
			result[0] = false;
			result[1] = "该网络设备不存在";
			return result;
		}
		
		Light light = new Light();
		light.setLightNum(lightNum.toUpperCase());
		
		String[] location = mapServer.locationTransfer(longitudeArr.toString(), latitudeArr.toString());
		
		// 根据经纬度获取地址
		String addressName = mapServer.queryAddressByLatAndLng(location[1], location[0]);
		if(addressName==null || "".equals(addressName)) {
			result[0] = false;
			result[1] = "没有获取到您的位置，添加失败！";
			return result;
		}
		
		Light lightObj = lightDao.queryLightByLightNumAndPanId(dtu.getPanId(), light.getLightNum());
		
		light.setAddressName(addressName);
		light.setLongitude(Double.valueOf(location[0]));
		light.setLatitude(Double.valueOf(location[1]));
		light.setDtuId(dtuId);
		light.setState(0);
		light.setOnlineState(0);
		light.setLightState(0);
		light.setCreateBy(dtu.getCreateBy());
		
		if(lightObj!=null) {
			light.setLightId(lightObj.getLightId());
			// 更新网络设备地址
			lightDao.updateLightLocation(light);
			result[0] = true;
			result[1] = "路灯位置更新成功！";
		}else {
			lightDao.addLight(light);
			result[0] = true;
			result[1] = "添加成功！";
		}
		
		return result;
	}
	
	public Object[] changeLocation(Integer lightId,String lat, String lng) {
		Object[] result = new Object[2];

		Light lightObj = lightDao.queryLightById(lightId);
		if(lightObj==null) {
			result[0] = false;
			result[1] = "设备不存在！";
			return result;
		}
		
		String addressName = mapServer.queryAddressByLatAndLng(lat, lng);
		if(addressName==null || "".equals(addressName)) {
			result[0] = false;
			result[1] = "没有获取到您的位置，添加失败！";
			return result;
		}
		
		lightObj.setLongitude(Double.valueOf(lng));
		lightObj.setLatitude(Double.valueOf(lat));
		lightObj.setAddressName(addressName);
		
		lightDao.updateLightLocation(lightObj);
		result[0] = true;
		result[1] = "路灯位置更新成功！";
		
		return result;
	}
	
	public Object[] addLights(String dtuIdStr, String[] lightNumArr,Double[] longitudeArr, Double[] latitudeArr, Long userId) {
		Object[] result = new Object[2];
		
		Integer dtuId = Integer.valueOf(dtuIdStr);
		Dtu dtu = dtuDao.queryDtuById(dtuId);
		if(dtu==null) {
			result[0] = false;
			result[1] = "该网络设备不存在";
			return result;
		}
		
		List<Light> lightList = new ArrayList<Light>();
		
		for(int i=0; i<lightNumArr.length; i++) {
			Light light = new Light();
			light.setLightNum(lightNumArr[i].toUpperCase());
			
			// 根据经纬度获取地址
			String addressName = mapServer.queryAddressByLatAndLng(latitudeArr[i].toString(), longitudeArr[i].toString());
			if(addressName==null || "".equals(addressName)) {
				result[0] = false;
				result[1] = "填写的经纬度无效，请核实后重新填写！";
				return result;
			}
			
			Light lightObj = lightDao.queryLightByLightNumAndPanId(dtu.getPanId(),light.getLightNum());
			if(lightObj!=null) {
				continue;
			}
			
			light.setAddressName(addressName);
			light.setLongitude(longitudeArr[i]);
			light.setLatitude(latitudeArr[i]);
			light.setDtuId(dtuId);
			light.setState(0);
			light.setOnlineState(0);
			light.setLightState(0);
			light.setCreateBy(userId);
			
			lightList.add(light);
		}
		
		for(Light light : lightList) {
			lightDao.addLight(light);
		}
		
		result[0] = true;
		result[1] = "添加成功！";
		return result;
	}
	
	public String getLightJsonTree() {
		List<Light> lightList = lightDao.queryLightList();
		
		StringBuffer json = new StringBuffer();
		json.append("[");
		
		/*[
			{ id:1, pId:0, name:"随意勾选 1", open:true},
			{ id:11, pId:1, name:"随意勾选 1-1", open:true},
			{ id:111, pId:11, name:"随意勾选 1-1-1"},
			{ id:112, pId:11, name:"随意勾选 1-1-2"},
			{ id:12, pId:1, name:"随意勾选 1-2", open:true},
			{ id:121, pId:12, name:"随意勾选 1-2-1"},
			{ id:122, pId:12, name:"随意勾选 1-2-2"},
			{ id:2, pId:0, name:"随意勾选 2", checked:true, open:true},
			{ id:21, pId:2, name:"随意勾选 2-1"},
			{ id:22, pId:2, name:"随意勾选 2-2", open:true},
			{ id:221, pId:22, name:"随意勾选 2-2-1", checked:true},
			{ id:222, pId:22, name:"随意勾选 2-2-2"},
			{ id:23, pId:2, name:"随意勾选 2-3"}
		];*/
		
		Map<Integer, String> dtuMap = new HashMap<Integer, String>();
		for(Light light : lightList) {
			if(dtuMap.containsKey(light.getDtuId())) {
				continue;
			}
			
			dtuMap.put(light.getDtuId(), light.getAddressName());
		}
		
		if(dtuMap.size()==0) {
			return "[]";
		}
		
		Set<Entry<Integer, String>> dtuSet = dtuMap.entrySet();
		for(Entry<Integer, String> entry : dtuSet) {
			json.append("{ id:'").append("dtu_").append(entry.getKey()).append("', pId:0, name:'").append(entry.getValue()).append("', open:true},");
			
			for(Light light : lightList) {
				if(light.getDtuId().equals(entry.getKey())) {
					json.append("{ id:'").append(light.getLightId()).append("', pId:'").append("dtu_").append(entry.getKey()).append("', name:'").append(light.getLightNum()).append("'},");
				}
			}
		}
		
		json.deleteCharAt(json.length()-1);
		json.append("]");
		
		return json.toString();
	}
	
	public List<LightBean>  queryLightListByIds(String ids) {
		
		String[] idArr = ids.split(",");
		List<Integer> idList = new ArrayList<Integer>();
		for(String idStr : idArr) {
			idList.add(Integer.valueOf(idStr));
		}
		
		List<Light> lightList = lightDao.queryLightListByIds(idList);
		List<LightBean> lightBeanList = new ArrayList<LightBean>();
		
		if(lightList!=null) {
			for(Light light : lightList) {
				lightBeanList.add(convertLight2LightBean(light));
			}
		}
		
		return lightBeanList;
	}
	
	private LightBean convertLight2LightBean(Light light) {
		LightBean bean = new LightBean();
		bean.setLightId(light.getLightId());
		bean.setLightNum(light.getLightNum());
		bean.setAddressName(light.getAddressName());
		bean.setDtuId(light.getDtuId());
		bean.setBatteryVoltage(light.getBatteryVoltage());
		bean.setSolarPanelVoltage(light.getSolarPanelVoltage());
		bean.setTemperature(light.getTemperature());
		bean.setControllerState(light.getControllerState());
		bean.setCollectTime(light.getCollectTime()==null?"":DateUtil.timeFormat(light.getCollectTime()));
		bean.setChargeCurrent(light.getChargeCurrent());
		bean.setWorkCurrent(light.getWorkCurrent());
		bean.setOutputPower(light.getOutputPower());
		bean.setOnlineState(light.getOnlineState());
		bean.setLightState(light.getLightState());
		bean.setState(light.getState());
		
		return bean;
	}
	
	public boolean delLight(String lightId) {
		return lightDao.delLight(Integer.valueOf(lightId));
	}
	
	public Light queryLightById(String lightId) {
		return lightDao.queryLightById(Integer.valueOf(lightId));
	}
	
	public List<Light> queryLightListByDtuId(String dtuId) {
		return lightDao.queryLightListByDtuId(Long.valueOf(dtuId));
	}
	
	public List<LightBean> queryLightBeanListByDtuId(Long dtuId) {
		List<Light> lightList = lightDao.queryLightListByDtuId(dtuId);
		List<LightBean> lightBeanList = new ArrayList<LightBean>();
		
		if(lightList==null || lightList.size()==0) {
			return lightBeanList;
		}
		
		for(Light light : lightList) {
			lightBeanList.add(convertLight2LightBean(light));
		}
		
		return lightBeanList;
	}
	
	public boolean changeLightState(Integer lightId, Integer lightState) {
		int res = lightDao.changeLightState(lightId, lightState);
		if(res>0) {
			return true;
		}else {
			return false;
		}
	}
	
	public boolean changeLightNum(Integer lightId, String lightNum) {
		return lightDao.changeLightNum(lightId, lightNum);
	}
	
	public int queryLightCountByDtuId(Long dtuId) {
		
		return 0;
	}
	
	public Light queryLightByLightNumAndPanId(String panId, String lightNum) {
		return lightDao.queryLightByLightNumAndPanId(panId, lightNum);
	}
}
